package com.dh.weibo.dao;

import com.dh.weibo.application.Application;
import com.dh.weibo.pojo.WeiBo;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class WeiBoDao {
    private List<WeiBo> weiBos = new ArrayList<>();


    {
        readLocal();
        if (weiBos.size() == 0) {// 第一次初始化
            WeiBo weiBo = new WeiBo("大家好，我是练习时长2年半的练习生", "鸡鸡鸡", "123456");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            WeiBo weiBo1 = new WeiBo("恭喜发财", "鸡你太美", "123456");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            WeiBo weiBo2 = new WeiBo("一行白鹭上青天", "两个黄鹂鸣翠柳", "123456");
            weiBos.add(weiBo);
            weiBos.add(weiBo1);
            weiBos.add(weiBo2);
        }


    }

    public WeiBoDao() {
        readLocal();
    }

    /**
     * 发布微博
     *
     * @param weiBo
     */
    public void publish(WeiBo weiBo) {
        weiBos.add(weiBo);
        saveLocal();
    }

    /**
     * 加载本地数据
     */
    public void readLocal() {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("F:\\IdeaProjects\\MyJava230203\\day25\\dir\\data.data"));
            weiBos = (List<WeiBo>) objectInputStream.readObject();
            objectInputStream.close();
        } catch (IOException e) {
            // 记录一下日志
        } catch (ClassNotFoundException e) {

        }
    }

    // 保存到本地
    public void saveLocal() {
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("F:\\IdeaProjects\\MyJava230203\\day25\\dir\\data.data"));
            objectOutputStream.writeObject(weiBos);
            objectOutputStream.flush();
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<WeiBo> getWeiBos() {
        return weiBos;
    }

    public WeiBo getWeiBoByID(String id) {
        for (WeiBo weiBo : weiBos) {
            if (weiBo.getId().equals(id)) {
                return weiBo;
            }
        }
        return null;
    }

    public void delete(WeiBo weiBo) {
        weiBos.remove(weiBo);
    }
}
